﻿using IdentityModel;
using MapleLeaf.IdentityServer.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace MapleLeaf.IdentityServer.Controllers {
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AccountController : BaseController {

        private readonly UserManager<ApplicationUser> _userManager;
        private readonly RoleManager<ApplicationRole> _roleManager;
        private readonly ApplicationDbContext _context;


        public AccountController(UserManager<ApplicationUser> user, RoleManager<ApplicationRole> role, ApplicationDbContext dbContext) {
            _userManager = user;
            _roleManager = role;
            _context = dbContext;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Login(MLUserModel model) {
            //_userManager.inser
           return Success("成功", "https://www.baidu.com/");
        }

        #region 用户
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        public IActionResult GetUserList() {
            var list = _userManager.Users.Where(x => !x.IsDelete).OrderByDescending(d => d.Id).ToList();
            return Success(list);
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddUserAsync(MLUserModel model) {

            string msg = "";
            var userItem = _userManager.FindByNameAsync(model.LoginName).Result;
            if (userItem == null) {
                var user = new ApplicationUser {
                    Email = model.Email,
                    UserName = model.Name,
                    LoginName = model.LoginName,
                    Sex = model.Sex,
                    Age = DateTime.Now.Year - model.Birth.Value.Year,
                    Birth = model.Birth,
                    Addr = "",
                    IsDelete = false
                };
                model.Password = "MapleLeaf888";
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded) {
                    //var entityEntry = new ApplicationUserRole { 
                    //   UserId = result.f
                    //};
                    //_ = _context.UserRoles.AddAsync(entityEntry).Result;

                    result = await _userManager.AddClaimsAsync(user, new Claim[]{
                            new Claim(JwtClaimTypes.Name, model.Name),
                            new Claim(JwtClaimTypes.Email, model.Email),
                            new Claim(JwtClaimTypes.EmailVerified, "false", ClaimValueTypes.Boolean),
                            new Claim(JwtClaimTypes.Role, "6"),
                            new Claim("rolename", "GENERAL"),
                        });
                    msg = result.Succeeded ? "添加用户成功!" : "添加用户失败!";
                }

            } else {
                msg = "用户已经存在";
            }
            return Fail(msg);
        }
        #endregion
        #region 角色
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        public IActionResult GetRoleList() {
            var list = _roleManager.Roles.Where(x => !x.IsDeleted).OrderByDescending(d => d.Id).ToList();
            return Success(list);
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddRoleAsync(MLRoleModel model) {
            var roleItem = _roleManager.FindByNameAsync(model.Name).Result;
            if (roleItem == null) {
                var role = new ApplicationRole {
                    Name = model.Name,
                    IsDeleted = false
                };
                var result = await _roleManager.CreateAsync(role);
                return result.Succeeded ? Success("添加角色成功!") : Fail("添加角色失败!");
            } else {
                return Fail("角色已经存在!");
            }
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DeleteRoleAsync(string Id) {
            var roleItem = _roleManager.FindByIdAsync(Id).Result;
            if (roleItem != null) {
                var result = await _roleManager.DeleteAsync(roleItem);
                return result.Succeeded ? Success("删除角色成功!") : Fail("删除角色失败!");
            } else {
                return Fail("角色不存在!");
            }
        }
        #endregion
    }
}

